package com.example.bookKeep.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.bookKeep.entity.Book;
import com.example.bookKeep.request.BookListRequest;
import com.example.bookKeep.request.DownloadRequest;
import com.example.bookKeep.response.base.Result;
import com.example.bookKeep.service.BookService;
import com.example.bookKeep.service.FileService;
import com.example.bookKeep.vo.*;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/book")
@Slf4j
public class BookController {

    @Autowired
    private BookService bookService;
    @Autowired
    private FileService fileService;

    @PostMapping("/add")
    public void add(@RequestBody Book book) {
        if (book.getId() == null) {
            book.setCreateTime(new Date());
        }
        book.setUpdateTime(new Date());
        bookService.saveOrUpdate(book);
    }

    @GetMapping("/detail")
    public Book detail(Integer id) {
        return bookService.getById(id);
    }

    @DeleteMapping("/removeById/{id}")
    public void removeById(@PathVariable("id") Integer id) {
        bookService.removeById(id);
    }

    @PostMapping("/list")
    public LinkedHashMap<LocalDate, List<Book>> list(@RequestBody BookListRequest bookListRequest) {
        List<Book> books = bookService.listByRequest(bookListRequest);
        // books按照bookDate分组

        LinkedHashMap<LocalDate, List<Book>> result = books.stream().collect(Collectors.groupingBy(Book::getBookDate, LinkedHashMap::new, Collectors.toList()));

        return result;
    }

    @PostMapping("/download")
    public Result<String> download(@RequestBody BookListRequest bookListRequest) throws IOException {
        List<Book> books = bookService.listByRequest(bookListRequest);
        @Cleanup ExcelWriter writer = ExcelUtil.getWriter();
        @Cleanup ByteArrayOutputStream stream = new ByteArrayOutputStream();
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("productName", "产品名称");
        map.put("productCategory", "型号");
        map.put("quantity", "数量");
        map.put("purchaser", "采购商");
        map.put("director", "经办人");
        map.put("recordType", "记录方式");
        map.put("bookDate", "送货日期");
        writer.setHeaderAlias(map);
        writer.setOnlyAlias(true);
        writer.write(books, true);
        writer.flush(stream, true);
        byte[] byteArray = stream.toByteArray();
        String s = fileService.uploadOss(new ByteArrayInputStream(byteArray), "xls");
        System.out.printf("生成文件:" + s);
        return Result.success("success", s);
// 关闭writer，释放内存
//此处记得关闭输出Servlet流
    }

    @GetMapping("/monthList")
    public List<Book> listByMonth(String ym) {
        return bookService.listByMonth(ym);
    }

    @GetMapping("/yearList")
    public List<Book> listByYear(String y) {
        return bookService.listByYear(y);
    }

    @GetMapping("/homeStatistics")
    public BookHomeVO homeStatistics(String ym) {
        return bookService.homeStatistics(ym);
    }

    @GetMapping("/monthStatistics")
    public StatisticsContainerVO monthStatistics(String ym) {
        return bookService.monthStatistics(ym);
    }

    @GetMapping("/monthDayNum")
    public List<BookMonthDayNumVO> monthDayNum(String ym) {
        return bookService.monthDayNum(ym);
    }

    @GetMapping("/yearStatistics")
    public StatisticsContainerVO yearStatistics(String ym) {
        return bookService.yearStatistics(ym);
    }

    @GetMapping("/listPurchaser")
    public List<String> listPurchaser() {
        return bookService.listPurchaser();
    }


    @GetMapping("/listDirector")
    public List<String> listDirector() {
        return bookService.listDirector();
    }
}
